from fastapi import APIRouter, Depends
from sqlalchemy import text
from sqlalchemy.exc import ArgumentError

from models import Schema, Entity, Value
from sqlalchemy.orm import Session
from models.db import get_db

from models.dashboard import Dashboard
from schemas import response_success, response_error
from schemas.dashboard import RawQuerySchema, DashboardCreateSchema, SQLQuerySchema

router = dashboard_router = APIRouter()


@router.get("")
async def dashboard_create(db: Session = Depends(get_db)):
    db_dashboard = db.query(Dashboard).all()
    return response_success(data={'list': db_dashboard})


@router.post("")
async def dashboard_create(form: DashboardCreateSchema, db: Session = Depends(get_db)):
    dashboard = Dashboard(content=form.content)
    db.add(dashboard)
    db.commit()
    return response_success("新增成功")

@router.put("/{id}")
async def dashboard_update(id: int, form: DashboardCreateSchema, db: Session = Depends(get_db)):
    db_dashboard = db.query(Dashboard).filter_by(id=id).first()
    db_dashboard.content = form.content
    db.commit()
    return response_success("更新成功")

@router.delete("/{id}")
async def dashboard_delete(id: int, db: Session = Depends(get_db)):
    db.query(Dashboard).filter_by(id=id).delete()
    db.commit()
    return response_success("删除成功")

@router.post("/raw_query")
async def dashboard_data(form: RawQuerySchema, db: Session = Depends(get_db)):
    db_schema = db.query(Schema).filter_by(schema_id=form.schema_id).first()
    field_ids = {x.field_id: x for x in db_schema.field}

    filter1 = {
        'field': 'health',
        'comparison': 'ilike',
        'value': '异常'
    }
    # 定义比较操作符的映射
    comparison_map = {
        'ilike': lambda val: Value.value.ilike(f"%{val}%"),
        'like': lambda val: Value.value.like(f"%{val}%"),
        '=': lambda val: Value.value == val,
        '>': lambda val: Value.value > val,
        '<': lambda val: Value.value < val,
        '>=': lambda val: Value.value >= val,
        '<=': lambda val: Value.value <= val
    }
    # 获取对应的条件
    condition = comparison_map[filter1['comparison']](filter1['value'])

    db_entitys = db.query(Entity).filter_by(schema_id=db_schema.id).join(Value, Value.entity_id == Entity.id).filter_by(
        field_id=field_ids[filter1['field']].id).filter(condition).all()
    if not db_entitys:
        return response_error(msg="没有查询到数据")

    entity_ids = [entity.id for entity in db_entitys]
    db_values = db.query(Value).filter(Value.entity_id.in_(entity_ids)).all()

    # 将 Values 数据按 entity_id 分组
    value_map = {}
    for value in db_values:
        if value.entity_id not in value_map:
            value_map[value.entity_id] = {}
        value_map[value.entity_id][value.field_id] = value

    data = []
    # 构建响应数据
    for entity in db_entitys:
        row = {}
        value_fields = value_map.get(entity.id, {})

        for field in db_schema.field:
            if not field.meta.get('hidden'):
                value = value_fields.get(field.id)
                row[field.field_id] = value.value if value else ''
        row['instance_id'] = entity.entity_id
        data.append(row)

    return response_success(data={'list': data, 'field': db_schema.field})


@router.post("/sql_query")
async def dashboard_data(form: SQLQuerySchema, db: Session = Depends(get_db)):
    try:
        print(form.sql)
        db_data = db.execute(text(form.sql)).mappings().all()
    except ArgumentError as error:
        return response_error(msg='sql error: {}'.format(error))

    print(db_data)
    return response_success(data={'list': db_data})
